﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using GoTextPalm.Core.Data;
using GoTextPalm.Core.Localization;
using GoTextPalm.Core.Persistence;
using System.Threading;

namespace GoTextPalm.Gui
{
    public partial class MessagesSavedForm : LocalizedForm
    {
        private Service Service;
        private Logic logic;

        public MessagesSavedForm(Service Service)
        {
            logic = new Logic();
            logic.DeleteOperationEndedEvent += new Logic.DeleteOperationEndedHandler(Logic_DeleteOperationEnded);
            logic.ErrorCausedEvent += new Logic.ErrorCausedHandler(Logic_ErrorCaused);
            logic.StatusTextChangedEvent += new Logic.StatusTextChangedHandler(Logic_StatusTextChanged);

            this.Service = Service;
            InitializeComponent();
            LoadMessages();
            AddMenusToDictionary();
            AddColumnsToDictionary();
            UpdateResources();
        }

        protected override void AddColumnsToDictionary()
        {
            AddColumnToDictionary(clDate, "clDate");
            AddColumnToDictionary(clText, "clText");
            AddColumnToDictionary(clRcpt, "clRcpt");
        }

        protected override void AddMenusToDictionary()
        {
            AddMenuToDictionary(mnuDel, "mnuDel");
            AddMenuToDictionary(mnuOpen, "mnuOpen");
            AddMenuToDictionary(mnuCtxOpen, "mnuOpen");
            AddMenuToDictionary(mnuCtxDel, "mnuDel");
        }

        private void LoadMessages()
        {
            List<Message> Messages = Service.Messages;
            lstMessages.Items.Clear();
            foreach (Message m in Messages)
            {
                ListViewItem lvi = new ListViewItem(m.Now.ToString());
                lvi.SubItems.Add(m.Text);
                StringBuilder sb = null;
                foreach (MessageRecipient mr in m.Recipients)
                    if (sb == null)
                        sb = new StringBuilder(mr.Label + " <" + mr.Value + ">");
                    else
                        sb.Append(", " + mr.Label + " <" + mr.Value + ">");
                lvi.SubItems.Add(sb.ToString());
                lvi.Tag = m;
                lstMessages.Items.Add(lvi);
            }
            lstMessages.Refresh();
        }

        private void MessagesSavedForm_Load(object sender, EventArgs e)
        {
            if (customInputPanel.SipSupported)
            {
                customInputPanel.Screen = screen;
                customInputPanel.Refresh();
            }
        }

        private void lstMessages_ItemActivate(object sender, EventArgs e)
        {
            DialogResult = new NewMessageForm(Service, 
                (Message)lstMessages.Items[lstMessages.SelectedIndices[0]].Tag)
                .ShowDialog();
            Close();
        }

        private void mnuCtxOpen_Click(object sender, EventArgs e)
        {
            lstMessages_ItemActivate(sender, e);
        }

        private void mnuCtxDel_Click(object sender, EventArgs e)
        {
            lstMessages.Enabled = mnuOpen.Enabled = mnuDel.Enabled = false;
            logic.Message = (Message)lstMessages.Items[lstMessages.SelectedIndices[0]].Tag;
            new Thread(new ThreadStart(logic.DeleteProcedure)).Start();
        }

        private void mnuOpen_Click(object sender, EventArgs e)
        {
            lstMessages_ItemActivate(sender, e);
        }

        private void mnuDel_Click(object sender, EventArgs e)
        {
            mnuCtxDel_Click(sender, e);
        }


        private void Logic_StatusTextChanged(String text)
        {
            if (InvokeRequired)
            {
                Logic.StatusTextChangedHandler func = Logic_StatusTextChanged;
                Invoke(func, text);
                return;
            }
            if (!stsBar.Visible)
                stsBar.Visible = stsBar.ProgressStarted = true;
            stsBar.Text = text;
        }

        private void Logic_DeleteOperationEnded()
        {
            if (InvokeRequired)
            {
                Logic.DeleteOperationEndedHandler func = Logic_DeleteOperationEnded;
                Invoke(func);
                return;
            }
            stsBar.Visible = stsBar.ProgressStarted = false;
            lstMessages.Enabled = mnuOpen.Enabled = mnuDel.Enabled = true;
            Service.Messages.Remove(logic.Message);
            LoadMessages();
        }

        private void Logic_ErrorCaused(String text)
        {
            if (InvokeRequired)
            {
                Logic.ErrorCausedHandler func = Logic_ErrorCaused;
                Invoke(func, text);
                return;
            }
            stsBar.Visible = stsBar.ProgressStarted = false;
            lstMessages.Enabled = mnuOpen.Enabled = mnuDel.Enabled = true;

            MessageBox.Show(text, header.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
        }

        private class Logic
        {
            public delegate void StatusTextChangedHandler(String text);
            public event StatusTextChangedHandler StatusTextChangedEvent;

            public delegate void DeleteOperationEndedHandler();
            public event DeleteOperationEndedHandler DeleteOperationEndedEvent;

            public delegate void ErrorCausedHandler(String text);
            public event ErrorCausedHandler ErrorCausedEvent;

            public Message Message;

            public void DeleteProcedure()
            {
                FireStatusTextChanged(Utility.Tr("MessagesSavedForm_stsdel", "Deleting message ..."));
                try
                {
                    DBMessage.DeleteMessage(Message.ID.Value);
                    FireDeleteOperationEnded();
                }
                catch (DBException e)
                {
                    FireErrorCaused(String.Format(Utility.Tr("MessagesSaveForm_dbex", "Cannot delete message: {0}"), e.Message));
                }
            }

            private void FireStatusTextChanged(String text)
            {
                if (StatusTextChangedEvent != null)
                    StatusTextChangedEvent(text);
            }

            private void FireDeleteOperationEnded()
            {
                if (DeleteOperationEndedEvent != null)
                    DeleteOperationEndedEvent();
            }

            private void FireErrorCaused(String text)
            {
                if (ErrorCausedEvent != null)
                    ErrorCausedEvent(text);
            }
        }

        private void lstMessages_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool v = lstMessages.SelectedIndices.Count > 0;
            mnuOpen.Enabled = mnuDel.Enabled = v;
            lstMessages.ContextMenu = v ? ctxMenu : null;
        }
    }
}